package com.common.base.widget

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.CycleInterpolator
import android.view.animation.TranslateAnimation

import androidx.appcompat.widget.AppCompatEditText
import com.common.base.R
import com.common.base.utils.AppUtils

class CommonEditText : AppCompatEditText, View.OnFocusChangeListener, TextWatcher {
    /**
     * 右边icon按钮的引用
     */
    private var mRightIconDrawable: Drawable? = null

    /**
     * 控件是否有焦点
     */
    private var hasFocus: Boolean = false

    /**
     * 默认字体颜色
     */
    private var color = 0

    /**
     * 是否删除功能
     */
    private var isDelete = true

    /**
     * 是否设置密码明文显示
     */
    private var isPasswordVisible = false

    /**
     * 是否显示明文
     */
    private var isVisible = false

    /**
     * 需要分离手机号码
     */
    private var needDividePhone = false

    /**
     * 默认切割符号
     */
    private val defaultDivideSymbol = "-"

    /**
     * 切割符号
     */
    private var mDivide: String = defaultDivideSymbol

    /**
     * 存放切割下标
     */
    private val groupCoords = ArrayList<Int>()

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initAttributeSet(attrs)
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initAttributeSet(attrs)
        init()
    }

    private fun initAttributeSet(attrs: AttributeSet?) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.CommonEditText)
        mRightIconDrawable = ta.getDrawable(R.styleable.CommonEditText_ce_right_icon)
        isDelete = ta.getBoolean(R.styleable.CommonEditText_ce_right_isDelete, true)
        isPasswordVisible =
            ta.getBoolean(R.styleable.CommonEditText_ce_right_isPasswordVisible, false)
        needDividePhone = ta.getBoolean(R.styleable.CommonEditText_ce_right_needDividePhone, false)
        if (isPasswordVisible) {
            isDelete = false
        }
        ta.recycle()
    }

    /**
     * 设置明文/非明文显示
     */
    private fun setPasswordState() {
        if (isPasswordVisible) {
            if (isVisible) {
                //显示
                mRightIconDrawable = AppUtils.getDrawable(R.mipmap.af_bb)
                transformationMethod = HideReturnsTransformationMethod.getInstance()
            } else {
                //隐藏
                mRightIconDrawable = AppUtils.getDrawable(R.mipmap.ae_bb)
                transformationMethod = PasswordTransformationMethod.getInstance()
            }
            mRightIconDrawable!!.setBounds(
                0,
                0,
                mRightIconDrawable!!.intrinsicWidth,
                mRightIconDrawable!!.intrinsicHeight
            )
            setClearIconVisible(true)
        }
    }

    private fun init() {
        if (isInEditMode) {
            return
        }
        if (needDividePhone) {
            initPhoneGroupCoord()
        }
        setPasswordState()
        //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
        if (mRightIconDrawable == null) {
            mRightIconDrawable = compoundDrawables[2]
        }
        if (mRightIconDrawable == null) {
            mRightIconDrawable = AppUtils.getDrawable(R.drawable.base_vector_edit_del)
            mRightIconDrawable!!.setBounds(
                0,
                0,
                mRightIconDrawable!!.intrinsicWidth,
                mRightIconDrawable!!.intrinsicHeight
            )
        }
        //默认设置隐藏图标
        setClearIconVisible(false)
        //设置焦点改变的监听
        onFocusChangeListener = this
        //设置输入框里面内容发生改变的监听
        addTextChangedListener(this)
    }


    /**
     * 因为我们不能直接给EditText设置点击事件，所以我们用记住我们按下的位置来模拟点击事件
     * 当我们按下的位置 在 EditText的宽度 - 图标到控件右边的间距 - 图标的宽度 和
     * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标，竖直方向就没有考虑
     */
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            if (compoundDrawables[2] != null) {
                val touchable =
                    event.x > width - totalPaddingRight && event.x < width - paddingRight
                if (touchable) {
                    rightIconClick()
                }
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 右边的按钮点击
     */
    private fun rightIconClick() {
        if (isDelete) {
            this.setText("")
        }
        if (isPasswordVisible) {
            isVisible = !isVisible
            setPasswordState()
        }
        onRightIconClick?.onRightClick()
    }

    /**
     * 当EditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
     */
    override fun onFocusChange(v: View, hasFocus: Boolean) {
        this.hasFocus = hasFocus
        onTxtFocusChangeListener?.onFocus(hasFocus)
        if (hasFocus && text != null) {
            setClearIconVisible(text!!.isNotEmpty())
        } else {
            setClearIconVisible(false)
        }
    }


    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     */
    private fun setClearIconVisible(visible: Boolean) {
        val right = if (visible) mRightIconDrawable else null
        mRightIconDrawable?.apply {
            setBounds(0,0, intrinsicWidth, intrinsicHeight)
        }
        setCompoundDrawables(
            compoundDrawables[0],
            compoundDrawables[1], right, compoundDrawables[3]
        )
    }


    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    override fun onTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
        if (hasFocus) {
            if (color != 0) {
                this.setTextColor(color)
            }
//            dividePhoneStr(s)
            setClearIconVisible(s.isNotEmpty())
        }
    }


    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}


    override fun afterTextChanged(s: Editable) {

    }

    /**
     * 初始化切割手机号码的下标
     */
    private fun initPhoneGroupCoord() {
        groupCoords.add(3)
        groupCoords.add(8)
    }

    private var mLength = 0
    private var mLastLength = 0

    /**
     * 切割手机号码
     */
    //TODO 未完成
    private fun dividePhoneStr(str: CharSequence) {
        var s = str
        if (needDividePhone) {
            if (s.length <= mLength) {
                if (mLastLength == 0) {
                    mLastLength = s.length
                }
                if (groupCoords.contains(s.length - 1)) {
                    if (s.length < mLastLength) {
                        // delete
                        s = s.toString().substring(0, s.length - 1)
                        setText(s.toString())
                    } else if (s.length > mLastLength) {
                        // add
                        s = s.toString().substring(0, s.length - 1) + mDivide + s.toString()
                            .substring(s.length - 1)
                        setText(s.toString())
                    }
                }
            } else {
                s = s.toString().substring(0, s.length - 1)
                setText(s.toString())
            }
            setSelection(s.length)
            mLastLength = s.length
        }
    }

    /**
     * 显示错误
     */
    fun showError() {
        color = this.currentTextColor
        this.startAnimation(shakeAnimation(5))
        this.setTextColor(Color.RED)
    }

    /**
     * 晃动动画
     *
     * @param counts 1秒钟晃动多少下
     */
    private fun shakeAnimation(counts: Int): Animation {
        val translateAnimation = TranslateAnimation(0f, 10f, 0f, 0f)
        translateAnimation.interpolator = CycleInterpolator(counts.toFloat())
        translateAnimation.duration = 1000
        return translateAnimation
    }

    /**
     * 右边icon的点击事件
     */
    private var onRightIconClick: OnRightIconClickListener? = null

    fun setOnRightIconClickListener(onRightIconClick: OnRightIconClickListener) {
        this.onRightIconClick = onRightIconClick
    }

    interface OnRightIconClickListener {
        fun onRightClick()
    }

    private var onTxtFocusChangeListener: OnTxtFocusChangeListener? = null
    fun setOnTxtFocusChangeListener(onFocusChangeListener: OnTxtFocusChangeListener) {
        this.onTxtFocusChangeListener = onFocusChangeListener
    }

    interface OnTxtFocusChangeListener {
        fun onFocus(focus: Boolean)
    }

}